package com.xxxx.server.mq.consumer;

import com.rabbitmq.client.Channel;
import com.xxxx.server.config.RabbitConfig;
import com.xxxx.server.mq.send.SendMailManager;
import com.xxxx.server.pojo.MailLog;
import com.xxxx.server.service.IMailLogService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class MailConsumer {

    @Autowired
    private SendMailManager sendMailManager;
    @Autowired
    private IMailLogService mailLogService;

    /**
     * 消费者消费队列中的消息
     * 认为邮箱唯一
     * @param message
     * @param channel
     */
    @RabbitListener(queues = RabbitConfig.MAIL_QUEUE_NAME)
    public void consume(Message message, Channel channel) throws IOException {
        //获得消息内容
        String to = new String(message.getBody());
        //根据邮箱获得mailLog对象
        MailLog mailLog = mailLogService.selectInfoByEmail(to);
        if(null == mailLog || mailLog.getStatus() == 1){
            //保证幂等性
            return;
        }

        //获取递送标签
        MessageProperties messageProperties = message.getMessageProperties();
        long deliveryTag = messageProperties.getDeliveryTag();
        //发送邮件
        boolean result = sendMailManager.sendSimpleMail(to);
        if(result){
            //更新状态为递送成功
            mailLogService.updateStatusByMsgId(mailLog.getMsgId(),1);
            //消费确认
            channel.basicAck(deliveryTag,false);
        }else{
            //更新消息为投递失败状态
            mailLogService.updateStatusByMsgId(mailLog.getMsgId(),2);
            channel.basicNack(deliveryTag,false,true);
        }
    }
}
